<template>
  <div class="view_page" style="min-height: calc(100% - 20px);">
    <!--  新增/修改  -->
    <el-card class="box-card" v-loading="loading" element-loading-text="拼命加载中"
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.8)"
             style="min-height: 100%;">
      <!--卡片头部-->
      <div slot="header" class="clearfix">
        <!--左侧-->
        <div class="left">
          <div class="back-page">
            <div class="add-back" @click="back">
              <i class="fa fa-arrow-left" aria-hidden="true"></i>
              <span>
                {{(addtype=='add'?'新增':(addtype=='update'?'修改':'查看')) + '分组'}}
              </span>
            </div>
          </div>
        </div>
        <div class="right" v-if="addtype!='query'">
          <el-button type="primary" @click="submitAdd()">保存</el-button>
        </div>
      </div>
      <!--卡片内容-->
      <div class="card-centont">
        <el-form :model="detail_data" label-width="150px">
          <div v-for="(item,index) in formAddItemList" :key="index">
            <el-form-item
              v-if="item.type=='string'||item.type=='decimal'||item.type=='number'"
              :label="item.label">
              <el-input
                v-model="detail_data[item.key]"
                :placeholder="item.placeholder"
                clearable
                :type="item.type=='decimal'?'number':item.type"
                @input="(item.type=='decimal'||item.type=='number')?checkFormatNumFixed2(item.key,item.decimal_number):null"
                @blur="(item.type=='decimal'||item.type=='number')?tt(item.key):null"
                @mousewheel.native.prevent
                @DOMMouseScroll.native.prevent
                :disabled="addtype=='query'||item.isDisable"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="item.type=='textarea'" :label="item.label">
              <el-input v-model="detail_data[item.key]"
                        :placeholder="item.placeholder"
                        :type="item.type"
                        :disabled="addtype=='query'"
              ></el-input>
            </el-form-item>
            <el-form-item v-if="item.type=='switch'" :label="item.label">
              <el-switch v-model="detail_data[item.key]"
                         :disabled="addtype=='query'"
              ></el-switch>
            </el-form-item>
            <div v-if="item.type=='list'&&item.key=='monitor_list'">
              <monitor-setting-list :label-name="item.label"
                                    :default-select-arr="monitorSelectArr"
                                    :default-table-arr="selectedMonitorList"
                                    :is-warning="addtype!='query'"
                                    :is-drag-sort="addtype!='query'"
                                    @updateTableList="updateTableMonitorList"
                                    @updateSelectedList="updateSelectedMonitorList"
              ></monitor-setting-list>
            </div>
          </div>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
  import {
    Message
  } from 'element-ui';
  import Utils from '@/utils/index.js';
  import Sortable from 'sortablejs';
  import MonitorSettingList from '../components/monitor-setting-list';

  export default {
    name: 'MonitorAdd',
    components: {
      MonitorSettingList,
    },
    data() {
      return {
        // userInfo: JSON.parse(localStorage.getItem(
        //   this.$apis.getLocalKey().loginPersonnelInformation)),
        // userInfo_id: JSON.parse(localStorage.getItem(
        //   this.$apis.getLocalKey().loginPersonnelInformation)).data.id,
        loading: false,
        formAddItemList: [
          {
            key: 'name',
            label: '组名',
            placeholder: '',
            type: 'string',
            isDisable: false,
          },
          {
            key: 'monitor_list',
            label: '选择测点(多选)',
            placeholder: '',
            type: 'list',
            // decimal_number: 2,
            isDisable: false,
            monitor_list: [],
          },
        ],
        addtype: 'add',
        initDetailData: {},
        detail_data: {
          id: -1,
        },
        monitorSelectArr: [],
        monitorSelectKey: 0,
        props: {
          multiple: true,
          'expand-trigger': 'click',
          checkStrictly: false,
          value: "id",
          label: "name",
          children: 'children',
        },
        monitorTreeProps: {
          value: "id",
          label: "name",
          children: 'children',
        },
        selectedMonitorList: [],
        isRefreshDragSort: false,
        refreshDraySortMonitors: [],
        datePickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          },
        },
        monitorOptions: [],
        river_type: -1,
        river_id: -1,
        real_type: 1,
      }
    },
    mounted() {
      for (let i = 0; i < this.formAddItemList.length; i++) {
        let key_str = this.formAddItemList[i].key;
        if (this.detail_data[key_str] == undefined) {
          this.$set(this.detail_data, key_str, '');
        }
      }
      this.$set(this.detail_data, 'monitor_arr', []);
      this.initDetailData = this.detail_data;

    },
    created() {
      this.addtype = this.$route.query.type;
      this.river_type = this.$route.query.river_type || -1;
      this.real_type = this.$route.query.real_type || 1;
      this.river_id = this.$route.query.river_id || -1;
      this.getAllSelectList();

      if (this.addtype == "add") {
      }
      if (this.addtype == 'update' || this.addtype == 'query') {
        let data = this.$route.query.data;
        this.detail_data = data || this.initDetailData;
        this.monitorSelectArr = JSON.parse(data.data_id);
        this.selectedMonitorList = JSON.parse(data.data);
      }
      // if (this.addtype == 'add' || this.addtype == 'update') {
      //   // 初始化拖拽表格修改顺序
      //   this.initSortMonitorList();
      // }
    },
    methods: {
      updateTableMonitorList(params) {
        this.selectedMonitorList = params || [];
      },
      updateSelectedMonitorList(params) {
        this.monitorSelectArr = params || [];
      },
      getAllSelectList() {
        let data = {};
        this.$apis.unity_monitor_set_all(data).then(res => {
          if (res.result == 0) {
            this.monitorOptions = res.data;
          }
        });
      },
      // changeMonitorSelected(val) {
      //   let arr = [];
      //   for (let x = 0; x < val.length; x++) {
      //     let river_type = val[x][0];
      //     let river_id = val[x][1];
      //     let device_id = val[x][2];
      //     let monitor_id = val[x][3];
      //     let tmp = {};
      //     Object.assign(tmp, {
      //       river_type: river_type,
      //       river_id: river_id,
      //       device_id: device_id,
      //       monitor_id: monitor_id,
      //       name: '',
      //     });
      //     for (let i = 0; i < this.monitorOptions.length; i++) {
      //       let typeTmp = this.monitorOptions[i];
      //       if (typeTmp.id == river_type) {
      //         for (let j = 0; j < typeTmp.children.length; j++) {
      //           let riverTmp = typeTmp.children[j];
      //           if (riverTmp.id == river_id) {
      //             for (let k = 0; k < riverTmp.children.length; k++) {
      //               let deviceTmp = riverTmp.children[k];
      //               if (deviceTmp.id == device_id) {
      //                 for (let l = 0; l < deviceTmp.children.length; l++) {
      //                   let monitorTmp = deviceTmp.children[l];
      //                   if (monitorTmp.id == monitor_id) {
      //                     Object.assign(tmp, {
      //                       id: monitorTmp.id,
      //                       monitor_num: monitorTmp.name,
      //                       name: riverTmp.name + '' + deviceTmp.name,
      //                       // name: typeTmp.name + '' + riverTmp.name + ''
      //                       //   + deviceTmp.name,
      //                     });
      //                   }
      //                 }
      //               }
      //             }
      //           }
      //         }
      //       }
      //     }
      //     arr.push(tmp);
      //   }
      //   this.selectedMonitorList = arr;
      // },
      // deleteMonitorRow(index, rows) {
      //   const curDelRow = rows.splice(index, 1)[0];
      //   let t = [];
      //   t.push(curDelRow.river_type);
      //   t.push(curDelRow.river_id);
      //   t.push(curDelRow.device_id);
      //   t.push(curDelRow.monitor_id);
      //
      //   let currentInd = -1;
      //   this.monitorSelectArr.find((value, index, arr) => {
      //     if (JSON.stringify(value) == JSON.stringify(t)) {
      //       currentInd = index;
      //     }
      //   });
      //   if (currentInd != -1) {
      //     let tt = this.monitorSelectArr.slice();
      //     tt.splice(currentInd, 1);
      //     this.monitorSelectArr = tt;
      //   }
      // },
      // initSortMonitorList() {
      //   this.$nextTick(() => {
      //     const el = document.querySelectorAll(
      //       '.el-table__body-wrapper > table > tbody')[0]
      //     // const sortable = new Sortable(el, options);
      //     // 根据具体需求配置options配置项
      //     const sortable = new Sortable(el, {
      //       onStart: (evt) => {
      //         console.log('start drag')
      //       },
      //       onEnd: (evt) => { // 监听拖动结束事件
      //         // console.log(evt.oldIndex) // 当前行的被拖拽前的顺序
      //         // console.log(evt.newIndex) // 当前行的被拖拽后的顺序
      //         // 这里就可以写我们需要传给后台的逻辑代码
      //         // 我们有了 evt.oldIndex 和 evt.newIndex 这两个参数做索引，我们可以根据绑定在表格上面的 data 这个 Array 找到两个相应的记录。就可以针对数据进行操作啦。
      //         // 下面将拖拽后的顺序进行修改
      //         const currRow = this.selectedMonitorList.splice(evt.oldIndex,
      //           1)[0];
      //         this.selectedMonitorList.splice(evt.newIndex, 0, currRow)
      //         // console.log(JSON.stringify(this.selectedMonitorList));
      //       }
      //     })
      //   });
      // },
      // removeMonitorItem(item) {
      //   let keyObj = null, ind = -1;
      //   for (let i = 0; i < this.formAddItemList.length; i++) {
      //     if (this.formAddItemList[i].key == item.key) {
      //       keyObj = this.formAddItemList[i];
      //       ind = i;
      //     }
      //   }
      //   if (ind != -1) {
      //     keyObj[item.key].splice(ind, 1);
      //   }
      //   //
      //   // var index = this.dynamicValidateForm.domains.indexOf(item)
      //   // if (index !== -1) {
      //   //   this.dynamicValidateForm.domains.splice(index, 1)
      //   // }
      // },

      checkFormatNumFixed2(key, decimal_number) {
        // let regx = /^[0-9]+(.[0-9]{2})?$/;
        // if (decimal_number == -1) {
        //   decimal_number = 9999;
        //   regx = /^d*(?:.d{0,9999})?$/;
        // } else if (typeof decimal_number!="number"&& !decimal_number) {
        //   decimal_number = 2;
        //   regx = /^[0-9]+(.[0-9]{2})?$/;
        // } else if (typeof decimal_number=="number"&&!decimal_number){
        //   decimal_number = 0;
        //   regx = /[^\D]/g;
        // }
        // console.log(key, decimal_number);
        // console.log(this.detail_data[key])
        // console.log('key type='+(typeof this.detail_data[key]))
        // this.detail_data[key] =(this.detail_data[key]).replace(regx, '');

        if (this.detail_data[key] == 0 || this.detail_data[key] == '') {
          return
        }
        let regx = /^()*(\d+)\.(\d\d).*$/;
        if (typeof decimal_number != "number") {
          decimal_number = 2;
          regx = /^()*(\d+)\.(\d\d).*$/;
        } else {
          if (decimal_number == -1) {
            decimal_number = 9999;
            regx = /^()*(\d+)\.(\d{9999}).*$/;
          } else if (decimal_number == 0) {
            decimal_number = 0;
            regx = /[^\d]/g;
            this.detail_data[key] = (this.detail_data[key]).replace(regx, '');
            this.detail_data[key] = parseFloat(this.detail_data[key]);
            return;
          } else {
            decimal_number = 2;
            regx = /^()*(\d+)\.(\d\d).*$/;
          }
        }
        let checkPlan = "" + this.detail_data[key];
        checkPlan = checkPlan.replace(/[^\d.]/g, "") // 清除“数字”和“.”以外的字符
        .replace(/\.{2,}/g, ".") // 只保留第一个. 清除多余的
        .replace(/^\./g, "") // 保证第一个为数字而不是.
        .replace(".", "$#$")
        .replace(/\./g, "")
        .replace("$#$", ".");
        if (checkPlan.indexOf(".") < 0 && checkPlan !== "") {
          // 以上已经过滤，此处控制的是如果没有小数点，首位不能为类似于 01、02的金额
          checkPlan = parseFloat(checkPlan) + "";
        } else if (checkPlan.indexOf(".") >= 0) {
          checkPlan = checkPlan.replace(regx, "$1$2.$3"); // 只能输入两个小数
        }
        if (checkPlan > 1) {
          checkPlan = checkPlan
          .replace(/^0*/g, "") // 清除数字之前的0
        } else {
          checkPlan = checkPlan
          .replace(/^0*/g, "0") // 清除数字之前的0
        }
        this.detail_data[key] = checkPlan;
        this.detail_data[key] = parseFloat(this.detail_data[key]);
      },
      tt(key_str) {
        if (this.detail_data[key_str] != '') {
          this.detail_data[key_str] = parseFloat(this.detail_data[key_str])
        }
      },
      submitAdd() {
        let datas = this.detail_data;
        datas.id = (this.addtype != 'add') ? this.detail_data.id : null;

        let params = {
          river_type: this.river_type,
          real_type: this.real_type,
          river_id: this.river_id,
          name: datas.name,
          data: JSON.stringify(this.selectedMonitorList),
          data_id: JSON.stringify(this.monitorSelectArr),
        };
        Object.assign(params, {
          id: (this.addtype != 'add') ? this.detail_data.id : null,
        });
        if (params.name == '') {
          Message.warning('请填写组名')
          return
        }
        if (this.selectedMonitorList.length == 0) {
          Message.warning('请选择测点')
          return
        }

        if (this.addtype == 'add') {
          this.$apis.unity_monitor_set_add(params).then(res => {
            if (res.result == 0) {
              Message.success('添加成功')
              this.$router.back()
            }
          });
        } else if (this.addtype == 'update') {
          this.$apis.unity_monitor_set_update(params).then(res => {
            if (res.result == 0) {
              Message.success('修改成功')
              this.$router.back()
            }
          });
        }
      },
      back() {
        this.$router.back()
      },
      // //文件列表移除文件时的钩子
      // handleRemove(file, fileList) {
      //   this.fileList = fileList;
      //   let ids = [], urls = [];
      //   for (let i = 0; i < this.fileList.length; i++) {
      //     ids.push(this.fileList[i].id);
      //     urls.push(this.fileList[i].url);
      //   }
      //   this.fileIds = ids;
      //   this.fileImgUrls = urls;
      // },
      // //点击文件列表中已上传的文件时的钩子
      // handlePreview(file) {
      //   console.log(file);
      // },
      // //文件上传成功的钩子
      // handleAvatarSuccess(res, file, fileList) {
      //   console.log(res);
      //   this.fileList = fileList;
      //   let ids = [], urls = [];
      //   for (let i = 0; i < this.fileList.length; i++) {
      //     ids.push(this.fileList[i].id);
      //     urls.push(this.fileList[i].url);
      //   }
      //   this.fileIds = ids;
      //   this.fileImgUrls = urls;
      // },
      // //文件上传失败时的钩子
      // handleAvatarError(err, file) {
      //   // Message.error("文件上传失败，请稍后再试");
      //   this.dialogVisible = false;
      // },
      // //文件超出一个
      // numberExceeded() {
      //   Message.error("文件上传超出限制数量了！");
      // },
      // //上传文件之前的钩子
      // beforeAvatarUpload(file) {
      //   var typeList = ["image/jpeg", "image/png", "image/jpg"];
      //   // const isJPG = file.type === 'image/jpeg'
      //   const isJPG = typeList.includes(file.type);
      //   const isLt2M = file.size / 1024 / 1024 < 10;
      //
      //   if (!isJPG) {
      //     this.$message.error("上传图片只能是 JPG或者PNG 格式!");
      //   }
      //   if (!isLt2M) {
      //     this.$message.error("上传文件大小不能超过 10MB!");
      //   }
      //   return isJPG && isLt2M;
      // },
    }
  }
</script>

<style>

</style>
